package com.ivy.wechatforclient.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.ivy.wechatforclient.R;
import com.ivy.wechatforclient.adapter.MessageAdapter;
import com.ivy.wechatforclient.entity.Message;
import com.ivy.wechatforclient.utils.HttpUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Lenovo on 2017/12/6.
 */

public class ChatActivity extends AppCompatActivity {

    private List<Message> msgList = new ArrayList<>();
    private EditText inputText;
    private Button btn_send;
    private RecyclerView msgRecyclerView;
    private MessageAdapter msgAdapter;
    private TextView tv_friend;
    private Map<String,String> m;
    private String sender;
    private String receiver;
    private String path_chat = "http://192.168.49.36:8080/WeChatForServer/MessageServlet";
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        sender = getIntent().getStringExtra("sender");
        receiver = getIntent().getStringExtra("receiver");

        Thread chatThread = new Thread(new ChatThread());
        chatThread.start();
        //initMsgs();
        init();


        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        msgRecyclerView.setLayoutManager(layoutManager);
        msgAdapter = new MessageAdapter(msgList,sender,receiver);
        msgRecyclerView.setAdapter(msgAdapter);
        m = new HashMap<String, String>();

        btn_send.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
            String content = inputText.getText().toString().trim();
            if (!"".equals(content)) {
                Message msg = new Message();
                msg.setSender(sender);
                msg.setReceiver(receiver);
                msg.setContent(content);
                m.put("sender",sender);
                m.put("receiver",receiver);
                m.put("content",content);
                new Thread(){
                    @Override
                    public void run() {
                        String result = HttpUtil.postByHttpClient(path_chat,m,"insert");
                    }
                }.start();

                msgList.add(msg);
                msgAdapter.notifyItemInserted(msgList.size() - 1);      //当有新消息时，刷新RecycleView中的显示
                msgRecyclerView.scrollToPosition(msgList.size() - 1);  //将RecycleView定位到最后一行
                inputText.setText("");  //清空输入框内容
            }
            }
        });

    }
    class ChatThread implements Runnable {

        @Override
        public void run() {
            try {
                Map<String ,String > params = new HashMap<String, String>();
                params.put("sender",sender);
                params.put("receiver",receiver);
                JSONArray arr = HttpUtil.postJSONArrayByURL(path_chat ,params, "show");
                for(int i = 0;i < arr.length();i++) {
                    JSONObject obj = arr.getJSONObject(i);
                    Message message = new Message();
                    message.setSender(obj.getString("sender"));
                    message.setReceiver(obj.getString("receiver"));
                    message.setContent(obj.getString("content"));
                    message.setType(obj.getInt("type"));
                    msgList.add(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void init() {
        inputText = (EditText) findViewById(R.id.et_input_text);
        btn_send = (Button) findViewById(R.id.btn_send);
        msgRecyclerView = (RecyclerView) findViewById(R.id.msg_recycler_view);
        tv_friend = (TextView) findViewById(R.id.tv_friend);
        tv_friend.setText(getIntent().getStringExtra("username"));
    }

    private void initMsgs() {
        Message msg1 = new Message("Hello guy.",Message.TYPE_RECEIVE);
        msgList.add(msg1);
        Message msg2 = new Message("Hello . Who is that?",Message.TYPE_SEND);
        msgList.add(msg2);
        Message msg3 = new Message("This is Tom. Nice to talk you.",Message.TYPE_RECEIVE);
        msgList.add(msg3);
    }
}
